package com.kld.generator.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.IoUtil;
import com.kld.common.annotation.Log;
import com.kld.common.core.controller.BaseController;
import com.kld.common.core.domain.PageQuery;
import com.kld.common.core.domain.R;
import com.kld.common.core.page.TableDataInfo;
import com.kld.common.enums.BusinessType;
import com.kld.common.utils.StringUtils;
import com.kld.generator.domain.GenTable;
import com.kld.generator.domain.GenTableColumn;
import com.kld.generator.service.IGenTableColumnService;
import com.kld.generator.service.IGenTableService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 代码生成 操作处理
 *
 * @author Lion Li
 */
@Validated
@Api(value = "代码生成", tags = {"代码生成管理"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/tool/gen")
public class GenController extends BaseController {

    private final IGenTableService genTableService;
    private final IGenTableColumnService genTableColumnService;

    @Value("${spring.datasource.dynamic.datasource.master.url}")
    private String url;

    /**
     * 查询代码生成列表
     */
    @ApiOperation("查询代码生成列表")
    @SaCheckPermission("tool:gen:list")
    @GetMapping("/list")
    public TableDataInfo<GenTable> genList(GenTable genTable, PageQuery pageQuery) {
        return genTableService.selectPageGenTableList(genTable, pageQuery);
    }

    /**
     * 查询指标代码生成列表
     */
    @ApiOperation("查询代码生成列表")
    @GetMapping("/indicatorGenList")
    public TableDataInfo<GenTable> indicatorGenList(GenTable genTable, PageQuery pageQuery) {
        return genTableService.selectIndicatorGenTableList(genTable, pageQuery);
    }

    /**
     * 修改代码生成业务
     */
    @ApiOperation("修改代码生成业务")
    @SaCheckPermission("tool:gen:query")
    @GetMapping(value = "/{talbleId}")
    public R<Map<String, Object>> getInfo(@PathVariable Long talbleId) {
        GenTable table = genTableService.selectGenTableById(talbleId);
        List<GenTable> tables = genTableService.selectGenTableAll();
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(talbleId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("info", table);
        map.put("rows", list);
        map.put("tables", tables);
        return R.ok(map);
    }

    /**
     * 查询数据库列表
     */
    @ApiOperation("查询数据库列表")
    @SaCheckPermission("tool:gen:list")
    @GetMapping("/db/list")
    public TableDataInfo<GenTable> dataList(GenTable genTable, PageQuery pageQuery) {
        return genTableService.selectPageDbTableList(genTable, pageQuery);
    }

    /**
     * 查询数据表字段列表
     */
    @ApiOperation("查询数据表字段列表")
    @SaCheckPermission("tool:gen:list")
    @GetMapping(value = "/column/{talbleId}")
    public TableDataInfo<GenTableColumn> columnList(Long tableId) {
        TableDataInfo<GenTableColumn> dataInfo = new TableDataInfo<>();
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        dataInfo.setRows(list);
        dataInfo.setTotal(list.size());
        return dataInfo;
    }

    /**
     * 导入表结构（保存）
     */
    @ApiOperation("导入表结构（保存）")
    @SaCheckPermission("tool:gen:import")
    @Log(title = "代码生成", businessType = BusinessType.IMPORT)
    @PostMapping("/importTable")
    public R<Void> importTableSave(String tables) {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList);
        return R.ok();
    }

    /**
     * 修改保存代码生成业务
     */
    @ApiOperation("修改保存代码生成业务")
    @SaCheckPermission("tool:gen:edit")
    @Log(title = "代码生成", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Void> editSave(@Validated @RequestBody GenTable genTable) {
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return R.ok();
    }

    /**
     * 删除代码生成
     */
    @ApiOperation("删除代码生成")
    @SaCheckPermission("tool:gen:remove")
    @Log(title = "代码生成", businessType = BusinessType.DELETE)
    @DeleteMapping("/{tableIds}")
    public R<Void> remove(@PathVariable Long[] tableIds) {
        genTableService.deleteGenTableByIds(tableIds);
        return R.ok();
    }

    /**
     * 预览代码
     */
    @ApiOperation("预览代码")
    @SaCheckPermission("tool:gen:preview")
    @GetMapping("/preview/{tableId}")
    public R<Map<String, String>> preview(@PathVariable("tableId") Long tableId) throws IOException {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return R.ok(dataMap);
    }

    /**
     * 生成代码（下载方式）
     */
    @ApiOperation("生成代码（下载方式）")
    @SaCheckPermission("tool:gen:code")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @GetMapping("/download/{tableName}")
    public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
        byte[] data = genTableService.downloadCode(tableName);
        genCode(response, data);
    }

    /**
     * 生成代码（自定义路径）
     */
    @ApiOperation("生成代码（自定义路径）")
    @SaCheckPermission("tool:gen:code")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @GetMapping("/genCode/{tableName}")
    public R<Void> genCode(@PathVariable("tableName") String tableName) {
        genTableService.generatorCode(tableName);
        return R.ok();
    }

    /**
     * 同步数据库
     */
    @ApiOperation("同步数据库")
    @SaCheckPermission("tool:gen:edit")
    @Log(title = "代码生成", businessType = BusinessType.UPDATE)
    @GetMapping("/synchDb/{tableName}")
    public R<Void> synchDb(@PathVariable("tableName") String tableName) {
        genTableService.synchDb(tableName);
        return R.ok();
    }

    /**
     * 批量生成代码
     */
    @ApiOperation("批量生成代码")
    @SaCheckPermission("tool:gen:code")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @GetMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = genTableService.downloadCode(tableNames);
        genCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"kld.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IoUtil.write(response.getOutputStream(), false, data);
    }


    /**
     * 新建指标业务表结构（保存）
     * @param genTable
     * @return
     */
    @ApiOperation("新建指标业务表结构（保存）")
    @Log(title = "新建指标代码", businessType = BusinessType.INSERT)
    @PostMapping("/indicatorTableSave")
    public R<Void> IndicatorTableSave(GenTable genTable) {
        List<GenTable> tableList = new ArrayList<GenTable>();
        genTable.setIndicatorFlag("1");//指标标识（1：是）
        tableList.add(genTable);
        int rows = genTableService.createTable(genTable);//创建指标代码表
        if(rows>-1){
            genTableService.importGenTable(tableList);//新增指标代码数据
        }
        return R.ok();
    }

    /**
     * 修改指标业务表结构（保存）
     * @param genTable
     * @return
     */
    @ApiOperation("修改指标业务表结构（保存）")
    @Log(title = "修改指标代码", businessType = BusinessType.UPDATE)
    @PostMapping("/indicatorTableUpdate")
    public R<Void> indicatorTableUpdate(GenTable genTable) {
        GenTable gt = genTableService.selectGenTableById(genTable.getTableId());
        if(gt!=null){
            gt.setUpdateTime(new Date());
            gt.setIndicatorTypeCode(genTable.getIndicatorTypeCode());
            gt.setTableName(genTable.getTableName());
            gt.setClassName(genTable.getClassName());
            gt.setDispOrder(genTable.getDispOrder());
            gt.setTableComment(genTable.getTableComment());
            genTableService.validateEdit(gt);
            genTableService.updateGenTable(gt);
        }
        return R.ok();
    }

    /**
     * 配置生成规则（保存）
     * @param genTableColumns
     * @return
     */
    @ApiOperation("配置生成规则（保存）")
    @Log(title = "配置生成规则", businessType = BusinessType.INSERT)
    @PostMapping("/indicatorColumnsSave")
    public R<Void> indicatorColumnsSave(@RequestBody List<GenTableColumn> genTableColumns) {
        List<GenTableColumn> genTableColumnsNew = new ArrayList<GenTableColumn>();
        if(genTableColumns.size()>0){
            for(GenTableColumn c: genTableColumns){
                if(StringUtils.isNotBlank(c.getIndicatorTypeCode())){
                    GenTable genTableNew = genTableService.selectGenTableByType(c.getIndicatorTypeCode());
                    c.setTableId(genTableNew.getTableId());
                    genTableColumnsNew.add(c);
                }else{
                    genTableColumnsNew.add(c);
                }
            }
            GenTable genTable = genTableService.selectGenTableById(genTableColumnsNew.get(0).getTableId());
            if(genTable!=null){
                List<GenTableColumn> genTableColumnList = genTableColumnService.selectGenTableColumnListNotIdByTableId(genTable.getTableId());
                if(genTableColumnList.size()>0){
                    genTableColumnService.dropColumn(genTable.getTableName(),genTableColumnList);//删除指标代码字段
                }
                if(genTableColumnsNew.size()>0){
                    genTableColumnService.createColumn(genTable.getTableName(),genTableColumnsNew);//创建指标代码字段
                    genTableColumnService.deleteGenTableColumnByTableId(genTable.getTableId());//删除指标代码数据
                    for(GenTableColumn tc:genTableColumnsNew){//添加指标代码数据
                        tc.setTableId(genTable.getTableId());
                        tc.setSort(1);
                        genTableColumnService.insertGenTableColumn(tc);
                    }
                }
            }
        }
        return R.ok();
    }


    /**
     * 校验原子指标业务表是否重复
     */
    @ApiOperation("校验原子指标业务表是否重复")
    @GetMapping("/validTableName")
    public R<Integer> validTableName(@Validated String value) {
        String tableSchema = url.split("/")[3].split("\\?")[0];
        return R.ok(genTableService.validTableName(value,tableSchema));
    }

    /**
     * 删除代码生成数据及删除表
     */
    @ApiOperation("删除代码生成数据及删除表")
    @SaCheckPermission("tool:gen:remove")
    @Log(title = "代码生成", businessType = BusinessType.DELETE)
    @DeleteMapping("/removeIndicator/{tableIds}")
    public R<Void> removeIndicator(@PathVariable Long[] tableIds) {
        List<String> tableNames = new ArrayList<String>();
        if(tableIds.length>0){
            for(Long tableId:tableIds){
                GenTable genTable =genTableService.selectGenTableById(tableId);
                tableNames.add(genTable.getTableName());
            }
        }
        int rows = genTableService.dropTable(tableNames);//删除指标代码表
        if(rows>-1){
            genTableService.deleteGenTableByIds(tableIds);//删除指标代码数据
        }
        return R.ok();
    }
}
